import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class frmMain extends JFrame {

	private JPanel contentPane;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frmMain frame = new frmMain();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public frmMain() {
		setTitle("Lab9 - V\u1EBD \u0111\u1ED3 th\u1ECB");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 653, 388);
		final Dimension dim = this.getSize();
		contentPane = new JPanel() {
			@Override
			public void paint(Graphics g) {
				// TODO Auto-generated method stub
				super.paint(g);
				Graphics2D g2 = (Graphics2D)g;
				g2.setStroke(new BasicStroke(3));
				Plotter sin = new PlotSin();
				sin.init(dim.width, dim.height, Color.green);
				sin.paint(g2);
				Plotter cos = new PlotCos();
				cos.init(dim.width, dim.height, Color.blue);
				cos.paint(g2);
				Plotter bac2 = new PlotBac2();
				bac2.init(dim.width, dim.height, Color.yellow);
				bac2.paint(g2);
			}
		};
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
	}

}

abstract class Plotter {
	protected int xOrigin, yOrigin;
	protected int xRatio, yRatio;
	protected Dimension dim;
	protected Color color;

	abstract double func(double x);

	protected void paint(Graphics g) {
		drawCoordinates(g);
		plotFunction(g);
	}
	
	private void plotFunction(Graphics g) {
		g.setColor(color);
		for (int px = 0; px < dim.width; px++) {
			try {
				double x = (double) (px - xOrigin) / (double) xRatio;
				double y = func(x);
				int py = yOrigin - (int) (y * yRatio);
				g.fillOval(px - 1, py - 1, 3, 3);
			} catch (Exception ex) {

			}
		}
	}

	public void init(int width, int height, Color color){
		xRatio = yRatio = 100;
		this.color= color;
		dim = new Dimension(width, height);
		xOrigin = dim.width/2;
		yOrigin = dim.height/2;
	}
	
	private void drawCoordinates(Graphics g) {
		g.setColor(Color.black);
		g.drawLine(xOrigin, 0, xOrigin, dim.height);
		g.drawLine(0, yOrigin, dim.width, yOrigin);
		g.drawString("0", xOrigin + 5, yOrigin + 15);
	}
}
class PlotSin extends Plotter{

	@Override
	double func(double x) {
		return Math.sin(x);
	}
}
class PlotCos extends Plotter{

	@Override
	double func(double x) {
		return Math.cos(x);
	}
}
class PlotBac2 extends Plotter{

	@Override
	double func(double x) {
		return 2*x*x;
	}
}
